﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using Flockmaster;

namespace 数据库复制工具toSQLServer
{
    public partial class Form1 : Form_Parent
    {
        private ClassJiami clsJM = new ClassJiami();
        private Rijndael_ ri = new Rijndael_("fdas$#2(_)(+$#FSF$@#$@!$@#^#$");
        private string m_sRst = string.Empty;
        private int HasCopyCont = 0;
        int TableCount;

        public Form1()
        {
            InitializeComponent();
        }

        private void SrcType_c_SelectedValueChanged(object sender, EventArgs e)
        {
            srcType = (DBTypes)SrcType_c.SelectedIndex;
            if (srcType == DBTypes.Oracle)
            {
                SrcDataBase_comboBox.DropDownStyle = ComboBoxStyle.Simple;
                label5.Text = "服务名：";
                label5.Location = new Point(40, 129);
                SrcIP_textBox.Width = 164;
                button8.Enabled = false;
                button8.Visible = false;
                SrcDataBase_comboBox.Enabled = true;
                label2.Text = "服务器地址：";
                SrcUser_Textbox.Enabled = true;
            }
            else if (srcType == DBTypes.Access)
            {
                SrcIP_textBox.Width = 140;
                button8.Enabled = true;
                button8.Visible = true;
                SrcDataBase_comboBox.Enabled = false;
                label2.Text = "  文件路径：";
                SrcUser_Textbox.Enabled = true;
            }
            else if (srcType == DBTypes.SQLCE)
            {
                SrcDataBase_comboBox.DropDownStyle = ComboBoxStyle.Simple;
                label5.Text = "  最大尺寸：";
                //label5.Location = new Point(40, 129);
                SrcIP_textBox.Width = 140;
                button8.Enabled = true;
                button8.Visible = true;
                SrcDataBase_comboBox.Enabled = true;
                label2.Text = "  文件路径：";
                SrcUser_Textbox.Enabled = false;
            }
            else
            {
                SrcDataBase_comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                label5.Text = "选择数据库：";
                label5.Location = new Point(15, 129);
                SrcIP_textBox.Width = 164;
                button8.Enabled = false;
                button8.Visible = false;
                SrcDataBase_comboBox.Enabled = true;
                label2.Text = "服务器地址：";
                SrcUser_Textbox.Enabled = true;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dt.Columns.Add("TName");
            dt.Columns.Add("NeedColumn");
            dt.Columns.Add("Fliter");

            ClassJiami jiami = new ClassJiami();
            string HostId = ZhuanH(jiami.Encrypto(ZhuanH(GetCpuID().ToUpper())).ToUpper(), true);
            RegistryKey_Operate reg = new RegistryKey_Operate("NetWorkScan");
            string RegInfo = "";

            if (reg.IsRegeditExit("RegisteredValue"))
            {
                RegInfo = reg.GetRegistData("RegisteredValue");
            }
            if (RegInfo == "" || HostId != RegInfo)
            {
                RegInfo_Form regForm = new RegInfo_Form();
                regForm.ShowDialog();
                if (regForm.DialogResult != DialogResult.Yes)
                {
                    //Face_Close();
                    this.Close();
                    return;
                }
            }

            SrcType_c.SelectedIndex = 0;
            destType_c.SelectedIndex = 0;

            db.End += new EventHandler<MyEventArgs>(Idb_End);
            db.ReportsProgress += new EventHandler<MyEventArgs>(Idb_ReportsProgress);
            db.ReceiveErrorMeaaage += new EventHandler<ErrorEventArgs>(Idb_ReceiveErrorMeaaage);
        }

        void Idb_ReceiveErrorMeaaage(object sender, ErrorEventArgs e)
        {
            richTextBox1.AppendText(e.Message + "\r\n");
        }

        void Idb_ReportsProgress(object sender, MyEventArgs e)
        {
            label11.Text = e.Count.ToString();
            progressBar1.Value = e.Count;
        }

        void Idb_End(object sender, MyEventArgs e)
        {
            if (HasCopyCont < TableCount)
            {
                if (!db.ISStop)
                {
                    ControAllControls(true);
                    Messages.Clear();
                    MessageBox.Show("终止了复制工作！");
                    return;
                }
                SendCmd cmd = new SendCmd();
                cmd.IsOnlyTableStructure = checkBox2.Checked;
                cmd.TableName = Messages[HasCopyCont].TableName;
                cmd.SqlCmd = Messages[HasCopyCont].GetSqlCmd();
                StartCopyTable(cmd);
                HasCopyCont++;
                label13.Text = String.Format("({0}/{1})", HasCopyCont, TableCount.ToString());
            }
            else
            {
                ControAllControls(true);
                Messages.Clear();
                MessageBox.Show("成功完成复制工作！");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                db.CreateConn(SrcIP_textBox.Text.Trim(), SrcUser_Textbox.Text.Trim(), SrcPWD_textBox.Text.Trim(), SrcDataBase_comboBox.Text.Trim(), srcType, ref db.srcConnection);
                if (srcType == DBTypes.Oracle || srcType==DBTypes.Access || srcType == DBTypes.SQLCE)
                {
                    db.CreateConn(SrcIP_textBox.Text.Trim(), SrcUser_Textbox.Text.Trim(), SrcPWD_textBox.Text.Trim(), SrcDataBase_comboBox.Text.Trim(), srcType, ref db.sysConnection);
                }
                if (db.srcConnection.State != ConnectionState.Open)
                {
                    db.srcConnection.Open();
                }
                if (srcType == DBTypes.Oracle)
                {
                    TableListBox.Items.Clear();
                    TableListBox.Items.AddRange(db.GetTableList(SrcIP_textBox.Text.Trim(), srcType,SrcUser_Textbox.Text.Trim()).ToArray());
                    string Count = string.Format("全部选择                       ({0})", TableListBox.Items.Count.ToString());
                    checkBox1.Text = Count;
                }
                if (srcType == DBTypes.Access || srcType== DBTypes.SQLCE)
                {
                    TableListBox.Items.Clear();
                    TableListBox.Items.AddRange(db.GetTableList(srcType).ToArray());
                    string Count = string.Format("全部选择                       ({0})", TableListBox.Items.Count.ToString());
                    checkBox1.Text = Count;
                }
                MessageBox.Show("成功打开源数据库！");
            }
            catch(Exception ex)
            {
                MessageBox.Show("无法建立源数据库连接，请确认提供的参数是否正确！\r\n异常信息："+ex.Message,"错误");
            }
        }


        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                db.CreateConn(DestIP_textBox.Text.Trim(), DestUser_Textbox.Text.Trim(), DestPWD_textBox.Text.Trim(), DestDataBase_comboBox.Text.Trim(), destType, ref db.destConnection);
                if (destType == DBTypes.Oracle || destType == DBTypes.Access || destType == DBTypes.SQLCE)
                {
                    db.CreateConn(DestIP_textBox.Text.Trim(), DestUser_Textbox.Text.Trim(), DestPWD_textBox.Text.Trim(), DestDataBase_comboBox.Text.Trim(), destType, ref db.sysConnection);
                }
                if (db.destConnection.State != ConnectionState.Open)
                {
                    db.destConnection.Open();
                }
                MessageBox.Show("成功打开源数据库！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法建立源数据库连接，请确认提供的参数是否正确！\r\n异常信息：" + ex.Message, "错误");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (Messages.Count == 0)
            {
                MessageBox.Show("请选择您需要同步的表！");
                return;
            }
            try
            {
                richTextBox1.Text = "";
                ControAllControls(false);
                Count = 0;
                HasCopyCont = 0;
                switch (destType)
                {
                    case DBTypes.SqlServer:
                        Idb = new SqlServer();
                        break;
                    case DBTypes.MySql:
                        Idb = new Flockmaster.MySql();
                        break;
                    case DBTypes.SQLCE:
                        Idb = new SqlCE();
                        break;
                    case DBTypes.Access:
                        Idb = new ACCESS();
                        break;
                    case DBTypes.Oracle:
                        Idb = new Oracle();
                        break;
                    default:
                        throw new Exception("未知数据库类型！");
                }
                Idb.End += new EventHandler<MyEventArgs>(Idb_End);
                Idb.ReceiveErrorMeaaage+=new EventHandler<ErrorEventArgs>(Idb_ReceiveErrorMeaaage);
                Idb.ReportsProgress+=new EventHandler<MyEventArgs>(Idb_ReportsProgress);

                Idb.CreateConn(SrcIP_textBox.Text.Trim(), SrcUser_Textbox.Text.Trim(), SrcPWD_textBox.Text.Trim(), SrcDataBase_comboBox.Text.Trim(), srcType, DBConnType.SrcConnection);
                if (Idb.SrcConnection.State != ConnectionState.Open)
                {
                    Idb.SrcConnection.Open();
                }

                Idb.CreateConn(DestIP_textBox.Text.Trim(), DestUser_Textbox.Text.Trim(), DestPWD_textBox.Text.Trim(),DestDataBase_comboBox.Text.Trim(), destType, DBConnType.DestConnection);
                if (Idb.DestConnection.State != ConnectionState.Open)
                {
                    Idb.DestConnection.Open();
                }
                TableCount = Messages.Count;
                SendCmd cmd = new SendCmd();
                cmd.TableName = Messages[0].TableName;
                cmd.SqlCmd = Messages[0].GetSqlCmd();
                cmd.IsOnlyTableStructure = checkBox2.Checked;
                db.ISStop = true;
                StartCopyTable(cmd);
                HasCopyCont++;
                label13.Text = String.Format("({0}/{1})", HasCopyCont, TableCount.ToString());
            }
            catch(Exception ex)
            {
                ControAllControls(true);
                MessageBox.Show(ex.Message);
            }
        }

        private void StartCopyTable(SendCmd Message)
        {
            progressBar1.Step = 0;
            progressBar1.Maximum = db.GetRowsCount(Message.TableName);

            //判断制定的表是否存在
            if (Idb.DoesTableExist(Message.TableName, destType))
            {
                if (MessageBox.Show("表" + Message.TableName + "已经在目标数据库存在，是否覆盖原有数据？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    Idb.DropTable(Message.TableName);
                }
                else
                {
                    return;
                }
            }
            Idb.CopyTable(Message);
        }


        /// <summary>
        /// 控制该启动该禁用的空间启用停用
        /// </summary>
        /// <param name="CanUse"></param>
        private void ControAllControls(bool CanUse)
        {
            foreach (Control a in groupBox1.Controls)
            {
                a.Enabled = CanUse;
            }
            foreach (Control b in groupBox3.Controls)
            {
                b.Enabled = CanUse;
            }
            button2.Enabled = CanUse;
            button7.Enabled = !CanUse;
            if (!CanUse)
            {
                progressBar1.Value = 0;
            }
            progressBar1.Enabled = CanUse;
            timer1.Enabled = !CanUse;
        }

        //填充Combox
        private void SrcDataBase_comboBox_Click(object sender, EventArgs e)
        {
            try
            {
                if (srcType != DBTypes.SQLCE && srcType != DBTypes.Oracle)
                {
                    bool TorF;
                    if (SrcDataBase_comboBox.Items.Count > 0)
                    {
                        SrcDataBase_comboBox.Items.Clear();
                        TorF = true;
                    }
                    else
                    {
                        TorF = false;
                    }

                    SrcDataBase_comboBox.Items.Clear();
                    if (SrcIP_textBox.Text == String.Empty || SrcUser_Textbox.Text == String.Empty || SrcPWD_textBox.Text == String.Empty)
                    {
                        return;
                    }
                    if (srcType != DBTypes.Oracle)
                    {
                        db.CreateSysConn(SrcIP_textBox.Text.Trim(), SrcUser_Textbox.Text.Trim(), SrcPWD_textBox.Text.Trim(), srcType);
                        SrcDataBase_comboBox.Items.AddRange(db.GetDataBaseList(db.sysConnection, srcType).ToArray());
                        if (!TorF)
                        {
                            SrcDataBase_comboBox.SelectedIndex = 0;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "警告");
            }
        }

        //获得表
        private void SrcDataBase_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (srcType != DBTypes.Oracle)
                {
                    TableListBox.Items.Clear();
                    string DatabaseName = SrcDataBase_comboBox.SelectedItem.ToString();
                    db.CreateConn(SrcIP_textBox.Text.Trim(), SrcUser_Textbox.Text.Trim(), SrcPWD_textBox.Text.Trim(), DatabaseName, srcType, ref db.srcConnection);
                    TableListBox.Items.AddRange(db.GetTableList(DatabaseName, srcType).ToArray());
                    string Count = string.Format("全部选择                       ({0})", TableListBox.Items.Count.ToString());
                    checkBox1.Text = Count;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"警告");
            }
        }

        private void DestDatabse_comboBox_Click(object sender, EventArgs e)
        {
            try
            {
                if (destType != DBTypes.Oracle && destType != DBTypes.SQLCE)
                {
                    DestDataBase_comboBox.Items.Clear();
                    if (DestIP_textBox.Text == String.Empty || DestUser_Textbox.Text == String.Empty || DestPWD_textBox.Text == String.Empty)
                    {
                        return;
                    }
                    db.CreateSysConn(DestIP_textBox.Text.Trim(), DestUser_Textbox.Text.Trim(), DestPWD_textBox.Text.Trim(), destType);
                    DestDataBase_comboBox.Items.AddRange(db.GetDataBaseList(db.sysConnection, destType).ToArray());
                    DestDataBase_comboBox.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "警告");
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox1.Checked == true)
            {
                for (int i = 0; i < this.TableListBox.Items.Count; i++)
                {
                    this.TableListBox.SetItemChecked(i, true);
                }
            }
            else
            {
                for (int i = 0; i < this.TableListBox.Items.Count; i++)
                {
                    this.TableListBox.SetItemChecked(i, false);
                }
            }
        }


        /// <summary>
        /// 用于注册信息验证的两个方法
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string ZhuanH(string text)
        {
            string cpuid = text;
            string Id = text;
            for (int i = 0; i < (cpuid.Length / 4) - 1; i++)
            {
                Id = Id.Insert(4 + (4 * i + i), "-");
            }
            return Id;
        }

        private string ZhuanH(string text, bool zhuce)
        {
            string temp = ZhuanH(text);
            int count = temp.LastIndexOf('-');
            string temp2 = "";
            for (int i = 0; i < count; i++)
            {
                temp2 += temp[i];
            }
            return temp2;
        }

        public String GetCpuID()
        {
            try
            {
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                String strCpuID = null;
                foreach (ManagementObject mo in moc)
                {
                    strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                    break;
                }
                return strCpuID;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "";
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            db.StopCopySession();
            ControAllControls(true);
        }

        private double Count = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            Count++;
            DateTime dt = new DateTime();
            dt = dt.AddSeconds(Count);
            Application.DoEvents();
            label14.Text = dt.ToLongTimeString();
        }

        private void TableListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            this.contextMenuStrip1.Visible = true;
        }

        private void 选择字段ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Messages.Clear();
            TableMessage _tables;
            for (int i = 0; i < TableListBox.CheckedItems.Count; i++)
            {
                _tables = new TableMessage();
                _tables.TableName = TableListBox.CheckedItems[i].ToString();
                Messages.Add(_tables);
            }
            Form_ChangeColumns fc = new Form_ChangeColumns();
            fc.Show();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            SrcIP_textBox.Text = openFileDialog1.FileName.Trim();
        }

        private void comboBox4_SelectedValueChanged(object sender, EventArgs e)
        {
            destType = (DBTypes)destType_c.SelectedIndex;
            if (destType == DBTypes.Oracle)
            {
                DestDataBase_comboBox.DropDownStyle = ComboBoxStyle.Simple;
                label6.Text = "服务名：";
                label6.Location = new Point(40, 129);
                DestIP_textBox.Width = 164;
                button9.Enabled = false;
                button9.Visible = false;
                DestDataBase_comboBox.Enabled = true;
                label9.Text = "服务器地址：";
                DestUser_Textbox.Enabled = true;
            }
            else if (destType == DBTypes.Access)
            {
                DestIP_textBox.Width = 140;
                button9.Enabled = true;
                button9.Visible = true;
                DestDataBase_comboBox.Enabled = false;
                label9.Text = "  文件路径：";
                DestUser_Textbox.Enabled = true;
            }
            else if (destType == DBTypes.SQLCE)
            {
                DestDataBase_comboBox.DropDownStyle = ComboBoxStyle.Simple;
                label6.Text = "  最大尺寸：";
                //label6.Location = new Point(40, 129);
                DestIP_textBox.Width = 140;
                button9.Enabled = true;
                button9.Visible = true;
                DestDataBase_comboBox.Enabled = true;
                label9.Text = "  文件路径：";
                DestUser_Textbox.Enabled = false;
            }
            else
            {
                DestDataBase_comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                label6.Text = "选择数据库：";
                label6.Location = new Point(15, 129);
                DestIP_textBox.Width = 164;
                button9.Enabled = false;
                button9.Visible = false;
                DestDataBase_comboBox.Enabled = true;
                label9.Text = "服务器地址：";
                DestUser_Textbox.Enabled = true;
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            DestIP_textBox.Text = openFileDialog1.FileName.Trim();
        }

        private void TableListBox_Leave(object sender, EventArgs e)
        {
            Messages.Clear();
            TableMessage _tables;
            for (int i = 0; i < TableListBox.CheckedItems.Count; i++)
            {
                _tables = new TableMessage();
                _tables.TableName = TableListBox.CheckedItems[i].ToString();
                Messages.Add(_tables);
            }
        }

        private void 剪切XToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 复制CToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

    }
}
